package com.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.entity.Product;
import com.form.Main2Form;

public class Main2Action extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Product> productList = null;

		Main2Form main2Form = (Main2Form) form;

		String productId = main2Form.getProductId();

		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/shangpin";
		String user = "root";
		String password = "rosy";

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, password);
			// Statement stmt = conn.createStatement();

			String sql = "select * from product where ProductId = ? ";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, productId);

			ResultSet rs = pstmt.executeQuery();

			productList = new ArrayList<Product>();
			// List<Product>

			while (rs.next()) {
				Product product = new Product();
				product.setProductId(rs.getString("ProductId"));
				product.setProductName(rs.getString("ProductName"));
				product.setProductKbnA(rs.getString("ProductKbnA"));
				product.setProductKbnB(rs.getString("ProductKbnB"));
				product.setProductKbnC(rs.getString("ProductKbnC"));
				product.setCostPrice(rs.getString("CostPrice"));
				product.setSellingPrice(rs.getString("SellingPrice"));
				product.setMaker(rs.getString("Maker"));
				product.setSupplier(rs.getString("Supplier"));
				product.setDummy1(rs.getString("Dummy1"));

				productList.add(product);
			}

			rs.close();
			// stmt.close();
			pstmt.close();
			// conn.close();

		} catch (ClassNotFoundException e) {
			System.out.println("Class not found");
		} catch (SQLException e) {
			System.out.println("Sql exception");
		} catch (Exception e) {
			System.out.println("exception");
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				response.getWriter().println(e.getMessage());
			}
		}

		request.setAttribute("products", productList);

		return mapping.findForward("success");

	}

}